package tests;

import common.Utils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;

import java.text.SimpleDateFormat;
import java.util.List;

public class EditPage extends Utils {
    public static String url = "http://8.137.19.140:9090/blog_edit.html";//登录成功的界面
    public EditPage() {
        super(url);
    }
    //正常发布博客
    public void editSuc() throws InterruptedException {
        //创建博客标题要随机生成，具备唯一性——方便后续继续精确校验
        SimpleDateFormat sim = new SimpleDateFormat("HH:mm:ss");
        String titleTime = sim.format(System.currentTimeMillis());
        String title = "自动测试标题"+titleTime;
        System.out.println("title="+title);
        //找到标题框输入标题
        driver.findElement(By.cssSelector("#title")).sendKeys(title);

        //这点就可能出现一种情况，在selenium中无法使用高级api Sendkeys对元素实现操作
        //解决办法
        //1）默认有内容，就不需要再输入内容
        //2）原生的键盘操作，而不使用api操作
        //通过原生的鼠标键盘操作来处理元素——Actions
        WebElement ele = driver.findElement(By.cssSelector("#editor > div.CodeMirror.cm-s-default.CodeMirror-wrap > div.CodeMirror-scroll > div.CodeMirror-sizer > div > div > div > div.CodeMirror-cursors"));
        Actions action = new Actions(driver);
        action.doubleClick(ele).sendKeys("Java115&Java116-autotest内容内容内容内容内容内容").perform();
        Thread.sleep(500);
        //点击发布
       driver.findElement(By.cssSelector("#submit")).click();
       //校验是否发布成功
        //获取所有博客标题
        List<WebElement> blogs = driver.findElements(By.cssSelector("body > div.container > div.right > div"));
        //校验标题是否存在
        String titleAfter = driver.findElement(By.cssSelector("body > div.container > div.right > div:nth-child("+blogs.size()+") > div.title")).getText();

        System.out.println("titleAfter="+titleAfter);
        assert titleAfter.equals(title);


    }
    //异常发布————不写标题

    public void editfail() throws InterruptedException {
        //点击写博客
        driver.findElement(By.cssSelector("body > div.nav > a:nth-child(5)")).click();
        //
        WebElement ele = driver.findElement(By.cssSelector("#editor > div.CodeMirror.cm-s-default.CodeMirror-wrap > div.CodeMirror-scroll > div.CodeMirror-sizer > div > div > div > div.CodeMirror-cursors"));
        Actions action = new Actions(driver);
        action.doubleClick(ele).sendKeys("没有标题的内容是否可以发布").perform();
        Thread.sleep(500);
        //点击发布
        driver.findElement(By.cssSelector("#submit")).click();
        //弹窗
        Thread.sleep(500);
        Alert alert = driver.switchTo().alert();

        //点击确定
        alert.accept();
        //重新填写标题
        driver.findElement(By.cssSelector("#title")).sendKeys("自动测试标题");
        //点击发布
        driver.findElement(By.cssSelector("#submit")).click();
    }

}
